<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="$t('sellerAnnualFee.editDia.年费规则管理')"
    width="800px"
    :showFooter="false"
  >
    <div class="annual-fee-container">
      <div class="header-actions mb-4">
        <el-button
          type="primary"
          @click="openAddDialog"
          v-my-point="'tenantRenewRule:add'"
          >{{ $t('sellerAnnualFee.editDia.添加规则') }}</el-button
        >
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column :label="$t('sellerAnnualFee.editDia.序号')" type="index" width="80" />
        <el-table-column prop="fee" :label="$t('sellerAnnualFee.editDia.费用')" width="180">
          <template #default="scope">
            ¥{{ parseFloat(scope.row.fee).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" :label="$t('sellerAnnualFee.editDia.持续时间(年)')" width="180" />
        <el-table-column :label="$t('sellerAnnualFee.editDia.操作')">
          <template #default="scope">
            <div class="operationBtnRow">
              <el-button
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
                v-my-point="'tenantRenewRule:edit'"
                >{{ $t('sellerAnnualFee.editDia.编辑') }}</el-button
              >
              <el-popconfirm
                :title="$t('sellerAnnualFee.editDia.确定删除此规则吗')"
                @confirm="handleDelete(scope.row)"
                :confirm-button-text="$t('sellerAnnualFee.editDia.确定')"
                :cancel-button-text="$t('sellerAnnualFee.editDia.取消')"
                width="260px"
              >
                <template #reference>
                  <el-button
                    class="ml0"
                    type="text"
                    size="small"
                    v-my-point="'tenantRenewRule:del'"
                    >{{ $t('sellerAnnualFee.editDia.删除') }}</el-button
                  >
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="currentRule.id ? $t('sellerAnnualFee.editDia.编辑规则') : $t('sellerAnnualFee.editDia.添加规则')"
      width="500px"
      append-to-body
    >
      <el-form
        :model="currentRule"
        :rules="rules"
        ref="ruleFormRef"
        label-width="100px"
      >
        <el-form-item :label="$t('sellerAnnualFee.editDia.费用')" prop="fee">
          <el-input-number
            v-model="currentRule.fee"
            :precision="2"
            :min="0"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('sellerAnnualFee.editDia.持续时间')" prop="duration">
          <el-input-number
            v-model="currentRule.duration"
            :min="1"
            :max="100"
            style="width: 100%"
          >
            <template #suffix>{{ $t('datePick.年') }}</template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">{{ $t('sellerAnnualFee.editDia.取消') }}</el-button>
          <el-button type="primary" @click="submitRuleForm">{{ $t('sellerAnnualFee.editDia.确定') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </Dialog>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const show = defineModel();

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 添加/编辑规则对话框
const ruleDialogVisible = ref(false);
const currentRule = ref({
  id: "",
  fee: 0,
  duration: 1,
});
const ruleFormRef = ref();

// 表单验证规则
const rules = {
  fee: [
    { required: true, message: t("sellerAnnualFee.editDia.请输入费用"), trigger: "blur" },
    { type: "number", min: 0, message: t("sellerAnnualFee.editDia.费用不能小于0"), trigger: "blur" },
  ],
  duration: [
    { required: true, message: t("sellerAnnualFee.editDia.请输入持续时间"), trigger: "blur" },
    { type: "number", min: 1, message: t("sellerAnnualFee.editDia.持续时间至少为1年"), trigger: "blur" },
  ],
};

// 当对话框打开时获取数据
watch(show, (val) => {
  if (val) {
    fetchData();
  }
});

// 获取年费规则列表
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await Api.tenantRenewRuleList({
      page: 0,
      size: 10000,
    });
    if (res.status === 200) {
      tableData.value = res.data.content || [];
    } else {
      ElMessage.error(res.message || t("sellerAnnualFee.editDia.获取年费规则失败"));
    }
  } catch (error) {
    console.error("获取年费规则失败", error);
    ElMessage.error(t("sellerAnnualFee.editDia.获取年费规则失败"));
  } finally {
    loading.value = false;
  }
};

// 打开添加规则对话框
const openAddDialog = () => {
  currentRule.value = {
    id: "",
    fee: 0,
    duration: 1,
  };
  ruleDialogVisible.value = true;
};

// 编辑规则
const handleEdit = (row) => {
  currentRule.value = JSON.parse(JSON.stringify(row));
  ruleDialogVisible.value = true;
};

// 删除规则
const handleDelete = async (row) => {
  try {
    await Api.deleteSellerAnnualFee([row.id]);
    ElMessage.success(t("sellerAnnualFee.editDia.删除成功"));
    fetchData();
  } catch (error) {
    ElMessage.error(t("sellerAnnualFee.editDia.删除失败"));
    console.error("删除年费规则失败", error);
  }
};

// 提交规则表单
const submitRuleForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentRule.value.id) {
          // 编辑
          await Api.updateSellerAnnualFee(currentRule.value);
          ElMessage.success(t("sellerAnnualFee.editDia.更新成功"));
        } else {
          // 添加
          await Api.addSellerAnnualFee(currentRule.value);
          ElMessage.success(t("sellerAnnualFee.editDia.添加成功"));
        }
        ruleDialogVisible.value = false;
        fetchData();
      } catch (error) {
        ElMessage.error(currentRule.value.id ? t("sellerAnnualFee.editDia.更新失败") : t("sellerAnnualFee.editDia.添加失败"));
        console.error(error);
      }
    }
  });
};

// 关闭主对话框
const handleSubmit = () => {
  close();
};

const close = () => {
  show.value = false;
};

// 组件挂载时获取数据
onMounted(() => {
  if (show.value) {
    fetchData();
  }
});
</script>

<style scoped lang="scss">
.annual-fee-container {
  padding: 0 10px;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.operationBtn {
  margin-right: 8px;
}
</style>
